package com.example.seh.add.post;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.textclassifier.TextLinks;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.seh.R;

import com.example.seh.constant.Constant;
import com.example.seh.databinding.ActivityAddPostBinding;
import com.example.seh.databinding.DialogChoosePicTypeBinding;
import com.example.seh.util.BackUtil;
import com.example.seh.util.JudgeContent;
import com.example.seh.util.UserMsg;

import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class AddPostActivity extends AppCompatActivity {

    private ActivityAddPostBinding addPostBinding;
    private String imgPath = "";
    private LinkedList<File> files = new LinkedList<>();

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        addPostBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_post);
        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        initEvent();
    }

    /**
     * Initial Event
     */
    private void initEvent() {
        /**
         * 点击上方返回键
         */
        addPostBinding.idleBack2.setOnClickListener(v -> {
            BackUtil.JumpBack(AddPostActivity.this);
        });

        /**
         * 点击发布按钮
         */
        addPostBinding.btnPublish2.setOnClickListener(v -> {
            if (Judge()){
                AlertDialog.Builder dialog = new AlertDialog.Builder(AddPostActivity.this);
                dialog.setTitle("提示")
                        .setMessage("确定要发布吗")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String content = addPostBinding.idleTitle.getText().toString()+addPostBinding.idleContent2.getText().toString();

                                JudgeContent.setData(content, new JudgeContent.DataCallback() {
                                    @Override
                                    public void onFailure() {
                                        Log.e("fail","发送失败");
                                    }

                                    @Override
                                    public void onResponse(String data) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(data);
                                            JSONArray wordList = jsonObject.getJSONArray("word_list");

                                            if (wordList.length() == 0) {
                                                sendData();
                                                BackUtil.Back(AddPostActivity.this);
                                                finish();
                                            } else {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(AddPostActivity.this,"发布内容包含敏感词汇，请修改后发布",Toast.LENGTH_LONG).show();
                                                    }
                                                });
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });

                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                dialog.create().show();
            }


        });

        /**
         * 设置标题字符限制(15个)
         */
        addPostBinding.idleTitle.setFilters(new InputFilter[]{new MyLengthFilter(15, getApplicationContext())});

        /**
         * 选择图片
         */
        addPostBinding.ivHelpImageFirst2.setOnClickListener(v -> {
            choosePictureDialog(10);
        });
        addPostBinding.ivHelpImageFirstDelete2.setOnClickListener(v -> {
            if (!files.isEmpty()){
                if (files.get(0) != null){
                    files.set(0,null);
                }
            }
            Log.e("files", files.toString());

            addPostBinding.ivHelpImageFirstDelete2.setVisibility(View.GONE);
            addPostBinding.ivHelpImageFirst2.setImageResource(R.mipmap.ic_upload_image);
        });
        addPostBinding.ivHelpImageSecond2.setOnClickListener(v -> {
            choosePictureDialog(11);
        });
        addPostBinding.ivHelpImageSecondDelete2.setOnClickListener(v -> {
            if (!files.isEmpty()){
                if (files.get(1) != null){
                    files.set(1,null);
                }
            }
            Log.e("files", files.toString());
            addPostBinding.ivHelpImageSecondDelete2.setVisibility(View.GONE);
            addPostBinding.ivHelpImageSecond2.setImageResource(R.mipmap.ic_upload_image);
        });
        addPostBinding.ivHelpImageThird2.setOnClickListener(v -> {
            choosePictureDialog(12);
        });
        addPostBinding.ivHelpImageThirdDelete2.setOnClickListener(v -> {
            if (!files.isEmpty()){
                if (files.get(2) != null){
                    files.set(2,null);
                }
            }
            Log.e("files", files.toString());
            addPostBinding.ivHelpImageThirdDelete2.setVisibility(View.GONE);
            addPostBinding.ivHelpImageThird2.setImageResource(R.mipmap.ic_upload_image);
        });
    }

    private boolean Judge() {
        String title = addPostBinding.idleTitle.getText().toString().trim();
        String content = addPostBinding.idleContent2.getText().toString().trim();

        if (title.isEmpty()) {
            Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (content.isEmpty()) {
            Toast.makeText(this, "请输入帖子内容", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    /**
     * 发布数据
     */
    private void sendData() {
        String  authorId = "3";
        String title = addPostBinding.idleTitle.getText().toString();
        String content = addPostBinding.idleContent2.getText().toString();

        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        requestBodyBuilder.addFormDataPart("title",title)
                .addFormDataPart("content",content)
                .addFormDataPart("authorId", String.valueOf(UserMsg.userDTO.getUserId()));


        for (File file : files) {
            if (file!=null&&file.getName() != null) {
                RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                requestBodyBuilder.addFormDataPart("files", file.getName(), requestBody);
            }
        }

        RequestBody requestBody2 = requestBodyBuilder.build();

        Request request = new Request.Builder()
                .url(Constant.ADD_POST)
                .header("Content-Type", "multipart/form-data")
                .post(requestBody2)
                .build();

        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("OkHttp","发送失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("OkHttp","发送成功");
            }
        });

    }

    /**
     * 判断用户输入字符长度
     */
    class MyLengthFilter implements InputFilter {

        private final int mMax;
        private Context context;

        public MyLengthFilter(int max, Context context) {
            mMax = max;
            this.context = context;
        }

        public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                   int dstart, int dend) {
            int keep = mMax - (dest.length() - (dend - dstart));
            if (keep <= 0) {
                //这里，用来给用户提示
                Toast.makeText(context, "字数不能超过" + mMax, Toast.LENGTH_SHORT).show();
                return "";
            } else if (keep >= end - start) {
                return null; // keep original
            } else {
                keep += start;
                if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                    --keep;
                    if (keep == start) {
                        return "";
                    }
                }
                return source.subSequence(start, keep);
            }
        }

        /**
         * @return the maximum length enforced by this input filter
         */
        public int getMax() {
            return mMax;
        }
    }

    /**
     * 选择拍照/相册图片
     *
     * @param type 打开类型区分码
     */
    private void choosePictureDialog(int type) {
        View chooseTypeView = LayoutInflater.from(this).inflate(R.layout.dialog_choose_pic_type, null);
        AlertDialog selectDialog = new AlertDialog.Builder(this).setView(chooseTypeView).setCancelable(false).create();
        selectDialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog
        selectDialog.show();

        //设置弹窗在底部
        Window window = selectDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.main_menu_animStyle);

        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
        WindowManager.LayoutParams p = selectDialog.getWindow().getAttributes(); //获取对话框当前的参数值
        p.width = d.getWidth(); //宽度设置为屏幕
        selectDialog.getWindow().setAttributes(p); //设置生效


        Objects.requireNonNull(selectDialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        DialogChoosePicTypeBinding binding = DataBindingUtil.bind(chooseTypeView);
        binding.tvChoosePicCamera.setOnClickListener(v -> {
            selectDialog.dismiss();
            // 拉起相机
            openCamera(type);
        });
        binding.tvChoosePicGallery.setOnClickListener(v -> {
            selectDialog.dismiss();
            // 打开相册
            openGallery(type);
        });
        binding.tvChoosePicCancel.setOnClickListener(v -> selectDialog.dismiss());
    }

    /**
     * 打开相机
     *
     * @param type 打开类型区分码
     */
    private void openCamera(int type) {
        // 创建照片存储目录
        File imgDir = new File(getFilePath(null));
        // 创建照片
        String photoName = System.currentTimeMillis() + ".png";
        File picture = new File(imgDir, photoName);
        if (!picture.exists()) {
            try {
                picture.createNewFile();
            } catch (IOException e) {
                Log.e("error", "choosePictureTypeDialog: 创建图片失败", e);
            }
        }
        imgPath = picture.getAbsolutePath();
        // 调用相机拍照
        Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        camera.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this, "com.example.seh.fileprovider", picture));
        startActivityForResult(camera, type);
    }

    /**
     * 打开相册
     *
     * @param type 打开类型区分码
     */
    private void openGallery(int type) {
        Intent gallery = new Intent(Intent.ACTION_PICK);
        gallery.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(gallery, type);
    }

    public String getRealPathFromURI(Uri uri) {
        String filePath = null;
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            if (inputStream != null) {
                File cacheDir = getCacheDir();
                File tempFile = File.createTempFile("image", null, cacheDir);
                tempFile.deleteOnExit();
                String tempFilePath = tempFile.getAbsolutePath();
                FileUtils.copyInputStreamToFile(inputStream, tempFile);
                filePath = tempFilePath;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拉起相机回调data为null，打开相册回调不为null
        switch (requestCode) {
            case 0:
                Toast.makeText(this, "权限获得", Toast.LENGTH_SHORT).show();
                break;
            case 10:
                if (resultCode == RESULT_CANCELED) {
                    return;
                } else {
                    if (data == null && !imgPath.isEmpty()) {
                        Glide.with(this).load(imgPath).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(addPostBinding.ivHelpImageFirst2);
                        Uri uri = Uri.fromFile(new File(imgPath));
                        if (!files.isEmpty()){

                                files.set(0,new File(imgPath));

                        }else {
                            files.add(0,new File(imgPath));
                        }
                        Log.e("files",files.toString());
                        System.out.println("10:" + uri);
                        addPostBinding.ivHelpImageFirstDelete2.setVisibility(View.VISIBLE);
                        addPostBinding.ivHelpImageSecond2.setVisibility(View.VISIBLE);
                    } else if (data.getData() != null) {
                        Glide.with(this).load(data.getData()).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(addPostBinding.ivHelpImageFirst2);
                        Uri selectedImage = data.getData();
                        String imagePath = getRealPathFromURI(selectedImage);
                        // 执行其他操作，例如添加到文件列表等
                        if (!files.isEmpty()){
                            // 执行其他操作，例如添加到文件列表等
                            files.set(0,new File(imagePath));
                        }else {
                            if (imagePath != null) {
                                // 执行其他操作，例如添加到文件列表等
                                files.add(0,new File(imagePath));
                            }
                        }
                        Log.e("files", files.toString());
                        addPostBinding.ivHelpImageFirstDelete2.setVisibility(View.VISIBLE);
                        addPostBinding.ivHelpImageSecond2.setVisibility(View.VISIBLE);
                    }
                }

                break;
            case 11:
                if (resultCode == RESULT_CANCELED) {
                    return;
                } else {
                    if (data == null && !imgPath.isEmpty()) {
                        Glide.with(this).load(imgPath).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(addPostBinding.ivHelpImageSecond2);
                        Uri uri = Uri.fromFile(new File(imgPath));
                        if (!files.isEmpty()) {
                            if (files.size() > 1) {
                                files.set(1, new File(imgPath));
                            } else {
                                files.add(1,new File(imgPath));
                            }
                        }
                        Log.e("files", files.toString());
                        addPostBinding.ivHelpImageSecondDelete2.setVisibility(View.VISIBLE);
                        addPostBinding.ivHelpImageThird2.setVisibility(View.VISIBLE);
                    } else if (data.getData() != null) {
                        Glide.with(this).load(data.getData()).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(addPostBinding.ivHelpImageSecond2);
                        Uri selectedImage = data.getData();
                        String imagePath = getRealPathFromURI(selectedImage);
                        if (!files.isEmpty()){
                            // 执行其他操作，例如添加到文件列表等
                            if (files.size()>1){
                                files.set(1,new File(imagePath));
                            }else {
                                if (imagePath != null) {
                                    // 执行其他操作，例如添加到文件列表等
                                    files.add(1,new File(imagePath));
                                }
                            }
                        }
                        Log.e("files", files.toString());
                        addPostBinding.ivHelpImageSecondDelete2.setVisibility(View.VISIBLE);
                        addPostBinding.ivHelpImageThird2.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case 12:
                if (resultCode == RESULT_CANCELED) {
                    return;
                } else {
                    if (data == null && !imgPath.isEmpty()) {
                        Glide.with(this).load(imgPath).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(addPostBinding.ivHelpImageThird2);
                        if (!files.isEmpty()){
                            if (files.size()>2){
                                files.set(2,new File(imgPath));
                            }else {
                                files.add(2,new File(imgPath));
                            }
                        }
                        Log.e("files", files.toString());
                        addPostBinding.ivHelpImageThirdDelete2.setVisibility(View.VISIBLE);
                    } else if (data.getData() != null) {
                        Glide.with(this).load(data.getData()).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(addPostBinding.ivHelpImageThird2);
                        Uri selectedImage = data.getData();
                        String imagePath = getRealPathFromURI(selectedImage);
                        if (!files.isEmpty()){
                            // 执行其他操作，例如添加到文件列表等
                            if (files.size()>2){
                                files.set(2,new File(imagePath));
                            }else {
                                if (imagePath != null) {
                                    // 执行其他操作，例如添加到文件列表等
                                    files.add(2,new File(imagePath));
                                }
                            }
                        }
                        Log.e("files", files.toString());

                        addPostBinding.ivHelpImageThirdDelete2.setVisibility(View.VISIBLE);
                    }
                }
                break;
            default:
                break;
        }
        imgPath = "";
    }

    /**
     * 获取存储文件路径
     *
     * @param dir 选择目录
     * @return 路径
     */
    public String getFilePath(String dir) {
        String path;
        // 判断是否有外部存储，是否可用
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            path = getExternalFilesDir(dir).getAbsolutePath();
        } else {
            // 使用内部储存
            path = getFilesDir() + File.separator + dir;
        }
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }
    /**
     *
     * 如果用户点了返回键
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            BackUtil.JumpBack(AddPostActivity.this);
        }
        return false;
    }

}